package com.zadtek.sharkRider.activity.common;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.zadtek.sharkRider.R;

public class Common {
	private static long lastClickTime;

	/**
	 * 按比例缩放图片大小
	 * 
	 * @param bmpOrg
	 *            图片数据
	 * @param ratioWidth
	 *            宽度缩放比率
	 * @param ratioHeight
	 *            高度缩放比率
	 * @return Bitmap 缩放图片
	 */
	public static Bitmap changeDrawRatio(Bitmap bmpOrg, double ratioWidth,
			double ratioHeight) {

		// 获取图片大小
		int width = bmpOrg.getWidth();
		int height = bmpOrg.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();

		// 设置缩放率
		matrix.postScale((float) ratioWidth, (float) ratioHeight);

		// 进行缩放，得到新图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bmpOrg, 0, 0, width, height,
				matrix, true);
		if (null != bmpOrg && !bmpOrg.isRecycled()) {
			bmpOrg.recycle();
		}
		return resizedBitmap;
	}

	/**
	 * 获得退出dialog框的构造
	 * 
	 * @param c
	 * @param title
	 * @param msg
	 */
	public static void createExitDialog(Context c, String title, String msg) {
		AlertDialog.Builder alert1 = new AlertDialog.Builder(c);
		alert1.setTitle(title).setMessage(msg)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create().show();
	}

	/**
	 * 获得确定dialog框的构造
	 * 
	 * @param c
	 * @param title
	 * @param msg
	 * @return AlertDialog
	 */
	public static AlertDialog getSureDialog(Context c, String title, String msg) {
		AlertDialog.Builder alert1 = new AlertDialog.Builder(c);
		return alert1.setTitle(title).setMessage(msg)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

					}
				}).create();
	}

	/**
	 * 获得Toast
	 * 
	 * @param context
	 *            画面控制器
	 * @param str
	 *            显示的信息
	 * @param time
	 *            显示时间 1 : 短时间 2 : 长时间
	 */
	public static void DisplayToast(Context context, String str, int time) {
		if (time == 1) {
			// 短时间显示Toast
			Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
		} else if (time == 2) {
			// 长时间显示Toast
			Toast.makeText(context, str, Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 自定义dialog,设定样式主题
	 * 
	 * @param c
	 * @param str
	 * @return ProgressDialog
	 */
	public static Dialog getTipDialog(Context c, int layoutResID, int theme) {

		final Dialog dialog = new Dialog(c, theme);
		dialog.setContentView(layoutResID);
		dialog.show();
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.RIGHT);
		lp.x = 0;
		lp.y = 0;
		dialogWindow.setAttributes(lp);
		dialog.setCanceledOnTouchOutside(true);
		return dialog;
	}

	/**
	 * 自定义dialog,设定宽度
	 * 
	 * @param c
	 * @param str
	 * @return ProgressDialog
	 */
	public static Dialog getTipDialog(Context c, int layoutResID, int w, int h) {

		final Dialog dialog = new Dialog(c, R.style.MyDialogStyle);
		dialog.setContentView(layoutResID);
		dialog.show();
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();

		lp.x = 0;
		lp.y = 0;
		if (w != 0) {
			lp.width = w; // 宽度
		}
		if (h != 0) {
			lp.height = h; // 高度
		}
		dialogWindow.setAttributes(lp);
		return dialog;
	}

	/**
	 * 判断wifi是否可用
	 * 
	 * @param inContext
	 *            上下文环境
	 * @return boolean true:可用 false:不可用
	 */
	public static boolean isWiFiActive(Context inContext) {
		Context context = inContext.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].isAvailable()) {
						if (info[i].getTypeName().equals("WIFI")
								&& info[i].isConnected()) {
							return true;
						}
					}
				}
			}
		}
		return false;
	}

	// 判断有没有网络
	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	public static boolean isFastDoubleClick() {

		long time = System.currentTimeMillis();

		long timeD = time - lastClickTime;

		if (0 < timeD && timeD < 800) {
			return true;
		}
		lastClickTime = time;

		return false;

	}

	// 获取网络图片得到bitmap
	public static Bitmap getHttpBitmap(String url) {
		URL myurl = null;
		InputStream in = null;
		Bitmap bitmap = null;
		try {
			myurl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
			conn.setConnectTimeout(0);
			conn.setDoInput(true);
			conn.connect();
			in = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bitmap;
	}

	/**
	 * 获取网落图片资源
	 * 
	 * @param url
	 * @return
	 */
	// 把一个url的网络图片变成一个本地的BitMap
	public Bitmap returnBitMap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	// 判断手机格式是否正确
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0,6-8])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);

		return m.matches();
	}

	// 判断email格式是否正确
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

	// 将时间戳转为字符串
	public static String getStrTime(String cc_time) {
		String re_StrTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		long lcc_time = Long.valueOf(cc_time);
		re_StrTime = sdf.format(new Date(lcc_time * 1000L));
		return re_StrTime;
	}
	
	//获取当天的时间
	public static String getToday() {
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String today = df.format(curDate);
		return today;
	}
	
	//获取本月的
	public static String getCurrMonth() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date datemon = new Date();
        String value = sdf.format(datemon);
        return value;
	}
	
	//获取上月的年月
	public static String getLastMonth() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date datemon = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(datemon);
        cal.add(Calendar.MONTH, -1);
        Date date = cal.getTime();
        String value = sdf.format(date);
        return value;
	}
	
	//获取昨天
	public static String getLastDay() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date datemon = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(datemon);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date date = cal.getTime();
        String value = sdf.format(date);
        return value;
	}
	
	// 将数字转化为大写  
    public static String numToUpper(int num) {  
        // String u[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};  
        String u[] = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" };  
        char[] str = String.valueOf(num).toCharArray();  
        String rstr = "";  
        for (int i = 0; i < str.length; i++) {  
            rstr = rstr + u[Integer.parseInt(str[i] + "")];  
        }  
        return rstr;  
    }  
  
    // 月转化为大写  
    public static String monthToUppder(int month) {  
        if (month < 10) {  
            return numToUpper(month);  
        } else if (month == 10) {  
            return "十";  
        } else {  
            return "十" + numToUpper(month - 10);  
        }  
    }

}
